package cn.pangza.web.utils;

import java.util.TimerTask;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

/**
 * 异步执行管理器
 * */
public class AsyncManager {

    /**
     * 延迟执行时间，单位与 execute 中的 TimeUnit 有关
     * */
    private final int OPERATE_DELAY_TIME = 10;

    /**
     * 初始化调度线程池
     */
    private ScheduledExecutorService executor = SpringUtil.getBean("pangzaScheduledExecutorService");

    private AsyncManager() {

    }

    /**
     * 单例
     * */
    private static AsyncManager me = new AsyncManager();

    /**
     * 构建单例模式
     */
    public static AsyncManager me() {return me;}

    /**
     * 执行定时器
     * */
    public void execute(TimerTask timerTask) {
        executor.schedule(timerTask, OPERATE_DELAY_TIME, TimeUnit.MICROSECONDS);
    }

    /**
     * 关闭线程池
     */
    public void shutdown() {
        Threads.shutdownAndAwaitTermination(executor);
    }
}
